package top.v5it.japi.plus.support;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;

/**
 * 应用于redis的lua脚本管理
 *
 * @author zhanpu
 * @date 20-12-2
 */
public final class LuaScriptUtil {


    private static final DefaultRedisScript<Long> LUA_UNLOCK_SCRIPT;
    private static final DefaultRedisScript<Long> LUA_RENEWAL_SCRIPT;
    private static final DefaultRedisScript<Long> LUA_LIMIT_WITH_COUNT_SCRIPT;
    private static final DefaultRedisScript<Long> LUA_LIMIT_WITH_WINDOW_SCRIPT;
    private static final DefaultRedisScript<Long> LUA_INCRSEQ_SCRIPT;

    static {
        LUA_UNLOCK_SCRIPT = new DefaultRedisScript<>();
        //用于解锁的lua脚本位置
        LUA_UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //返回值类型
        LUA_UNLOCK_SCRIPT.setResultType(Long.class);

        LUA_RENEWAL_SCRIPT = new DefaultRedisScript<>();
        //用于给锁续期的lua脚本位置
        LUA_RENEWAL_SCRIPT.setLocation(new ClassPathResource("renewal.lua"));
        //返回值类型
        LUA_RENEWAL_SCRIPT.setResultType(Long.class);

        LUA_LIMIT_WITH_COUNT_SCRIPT = new DefaultRedisScript<>();
        //用于限制流量lua脚本位置
        LUA_LIMIT_WITH_COUNT_SCRIPT.setLocation(new ClassPathResource("limit_with_count.lua"));
        //返回值类型
        LUA_LIMIT_WITH_COUNT_SCRIPT.setResultType(Long.class);

        LUA_LIMIT_WITH_WINDOW_SCRIPT = new DefaultRedisScript<>();
        //用于限制流量lua脚本位置
        LUA_LIMIT_WITH_WINDOW_SCRIPT.setLocation(new ClassPathResource("limit_with_window.lua"));
        //返回值类型
        LUA_LIMIT_WITH_WINDOW_SCRIPT.setResultType(Long.class);

        LUA_INCRSEQ_SCRIPT = new DefaultRedisScript<>();
        //用于获取自增序列lua脚本位置
        LUA_INCRSEQ_SCRIPT.setLocation(new ClassPathResource("incrseq.lua"));
        //返回值类型
        LUA_INCRSEQ_SCRIPT.setResultType(Long.class);
    }

    private LuaScriptUtil() {
        throw new UnsupportedOperationException();
    }

    /**
     * 分布式锁脚本
     *
     * @return
     */
    public static DefaultRedisScript<Long> getLuaUnlockScript() {
        return LUA_UNLOCK_SCRIPT;
    }

    /**
     * 分布式锁续期脚本
     *
     * @return
     */
    public static DefaultRedisScript<Long> getLuaRenewalScript() {
        return LUA_RENEWAL_SCRIPT;
    }

    /**
     * 限流脚本
     *
     * @return
     */
    public static DefaultRedisScript<Long> getLuaLimitWithCountScript() {
        return LUA_LIMIT_WITH_COUNT_SCRIPT;
    }

    /**
     * 限流脚本
     *
     * @return
     */
    public static DefaultRedisScript<Long> getLuaLimitWithWindowScript() {
        return LUA_LIMIT_WITH_WINDOW_SCRIPT;
    }

    /**
     * 自增两位序列号脚本
     *
     * @return
     */
    public static DefaultRedisScript<Long> getLuaIncrseqScript() {
        return LUA_INCRSEQ_SCRIPT;
    }


}
